from matplotlib.font_manager import json_dump, json_load
import os
import cv2
import numpy as np
# 将segment标签转化为rectangle标签
rect_label = {
    "label": "rect",
    "points": [],
    "group_id": None,
    "description": "",
    "shape_type": "rectangle",
    "flags": {},
    "mask": None
}


def do_label_pig_img(label_path:str):
    lebel_json = json_load(label_path)
    pig_segment = []
    for shpae in lebel_json["shapes"]:
        if shpae["label"] != "pig":
            continue
        pig_segment = shpae["points"]
    if len(pig_segment) == 0:
        return
    pig_segment = np.array(pig_segment,dtype=np.float32)
    x, y, w, h = cv2.boundingRect(pig_segment)
    rect_label["points"] = [float(x), float(y)],[float(x+w),float(y+h)],
    lebel_json["shapes"].append(rect_label)
    json_dump(lebel_json,label_path)

for root,dirs,files in os.walk("./240923_am"):
    for dir in dirs:
        label = f"./240923_am/{dir}/1280x720_MA.json"
        do_label_pig_img(label)
        